package log

import (
	"fmt"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)
var logger Logger
var logDir string = "C:\\Users\\\\03\\Desktop\\training-camp\\week13\\"
func init() {
	logger = NewLogger("week13.log")
}
func Debug(msg string, fields ...interface{}) {
	logger.Debug(msg,fields...)
}
func Info(msg string, fields ...interface{}) {
	logger.Info(msg,fields...)
}
func Warn(msg string, fields ...interface{}) {
	logger.Warn(msg,fields...)
}
func Error(msg string, fields ...interface{}) {
	logger.Error(msg,fields...)
}
func Fatal(msg string, fields ...interface{}) {
	logger.Fatal(msg,fields...)
}
type Logger interface {
	Debug(msg string, fields ...interface{})
	Info(msg string, fields ...interface{})
	Warn(msg string, fields ...interface{})
	Error(msg string, fields ...interface{})
	Fatal(msg string, fields ...interface{})
}

type ZapLogger struct {
	ZLog *zap.Logger
}

func (log *ZapLogger) Debug(msg string, fields ...interface{}) {
	log.ZLog.Sugar().Debugf(msg,fields...)
	defer log.ZLog.Sync()
}
func (log *ZapLogger) Info(msg string, fields ...interface{}) {
	log.ZLog.Sugar().Infof(msg,fields...)
	defer log.ZLog.Sync()
}
func (log *ZapLogger) Warn(msg string, fields ...interface{}) {
	log.ZLog.Sugar().Warnf(msg,fields...)
	defer log.ZLog.Sync()
}
func (log *ZapLogger) Error(msg string, fields ...interface{}) {
	log.ZLog.Sugar().Errorf(msg,fields...)
	defer log.ZLog.Sync()
}
func (log *ZapLogger) Fatal(msg string, fields ...interface{}) {
	log.ZLog.Sugar().Fatalf(msg,fields...)
	defer log.ZLog.Sync()
}
func newZapLogger(dir string) *ZapLogger{
	zp := &ZapLogger{}

	hook := lumberjack.Logger{
		Filename:   dir,  //日志文件路径
		MaxSize:    128, //最大字节
		MaxAge:     30,
		MaxBackups: 7,
		Compress:   true,
	}
	w := zapcore.AddSync(&hook)
	encoderConfig := zapcore.EncoderConfig{
		MessageKey: "msg",
		LevelKey:       "level",
		TimeKey:        "time",
		NameKey:        "name",
		CallerKey:      "line",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.FullCallerEncoder,
		EncodeName:     zapcore.FullNameEncoder,
	}

	core := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfig),
		w,
		zap.DebugLevel,
	)

	logger := zap.New(core,zap.AddCaller())
	zp.ZLog = logger
	//defer logger.Sync()
	return zp
}


func NewLogger(fileName string) Logger{
	logFile := logDir+fileName
	fmt.Println(logFile)
	return newZapLogger(logFile)
}